package com.lalameow.serverlogingate.service;

import com.lalameow.packet.pojo.ServerInfo;
import com.lalameow.serverlogingate.enetiy.GameServerInfo;
import com.lalameow.serverlogingate.repository.GameServerInfoRepository;
import com.lalameow.serverlogingate.utiles.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * 创建人: 陈刚
 * 日期: 2018/5/11
 * 时间: 12:16
 * 功能：请进行修改
 */
@Service
@Slf4j
public class GameServerInfoService {
    @Autowired
    private GameServerInfoRepository gameServerInfoRepository;
    public static ServerInfo[] serverInfos;

    public GameServerInfo save(String name,String host){
        GameServerInfo gameServerInfo=gameServerInfoRepository.findOne(name);
        if(gameServerInfo==null){
            gameServerInfo=new GameServerInfo();
            gameServerInfo.setServerName(name);
            gameServerInfo.setServerHost(host);
            gameServerInfo= gameServerInfoRepository.save(gameServerInfo);
            log.info("服务器【{}】保存成功,目前服务器为离线状态。",name);
            return gameServerInfo;
        }else {
            log.info("服务器名称重复【{}】,无法添加！",name);
        }
        return null;
    }


    public ServerInfo[] getAllServer(){
        List<GameServerInfo> gameServerInfoList=gameServerInfoRepository.findByOnline(true);
        if(gameServerInfoList!=null){
            ServerInfo[] serverInfos=new ServerInfo[gameServerInfoList.size()];
            for(int i=0;i<gameServerInfoList.size();i++){
                ServerInfo serverInfo=new ServerInfo();
                BeanUtil.beanCopy(gameServerInfoList.get(i),serverInfo);
                serverInfos[i]=serverInfo;
            }
            return serverInfos;
        }
        return null;
    }
    public void delete(String name){
        gameServerInfoRepository.delete(name);
    }

    public void online(String name){
        GameServerInfo gameServerInfo=gameServerInfoRepository.findOne(name);
        if(gameServerInfo!=null){
            gameServerInfo.setOnline(true);
            gameServerInfoRepository.save(gameServerInfo);
            log.info("服务器【{}】已上线",name);
        }else {
            log.info("服务器【{}】不存在！",name);
        }

    }
    public void offline(String name){
        GameServerInfo gameServerInfo=gameServerInfoRepository.findOne(name);
        if(gameServerInfo!=null){
            gameServerInfo.setOnline(false);
            gameServerInfoRepository.save(gameServerInfo);
            log.info("服务器【{}】已下线",name);
        }else {
            log.info("服务器【{}】不存在！",name);
        }

    }

}
